import {defineStore} from "pinia";
import {ref} from "vue";
import {useAccountStore} from "@/stores/account";
import {getUnreadCnt} from "@/api/path/message";

export const useSocketStore = defineStore('socket', () => {
    const ws = ref<WebSocket | null>(null);
    const unreadMessageCount = ref(0);

    const accountStore = useAccountStore();

    const refreshUnreadMessageCount = async () => {
        if (accountStore.hasLogin) {
            const response = await getUnreadCnt();
            if (response.errno === 1) {
                unreadMessageCount.value = response.count;
            }
        }
    }

    const connect = async () => {
        if (!accountStore.hasLogin) {
            console.log('[ws]当前未登录，无法建立连接');
            return;
        }
        if (ws.value && ws.value.readyState <= WebSocket.OPEN) {
            console.log('[ws]当前已连接，无需建立新连接');
            return;
        }

        await refreshUnreadMessageCount();

        // ws.value = new WebSocket(`ws://127.0.0.1:8000/ws/chat/${accountStore.user.id}/`); // 本地测试
        ws.value = new WebSocket(`ws://10.251.252.145:8000/ws/chat/${accountStore.user.id}/`); // 服务器

        ws.value.addEventListener('open', (event) => {
            console.log('[ws]连接建立', event);
        });
        ws.value.addEventListener('message', (event) => {
            const data = JSON.parse(event.data);
            console.log('[ws]收到消息', data);
            if (data.sender_id !== accountStore.user.id) {
                unreadMessageCount.value += 1;
            }
        });
        ws.value.addEventListener('close', (event) => {
            console.log('[ws]连接关闭', event);
            connect();
        });
        ws.value.addEventListener('error', (event) => {
            console.log('[ws]发生错误，准备重连', event);
            connect();
        });
    }

    const disConnect = () => {
        if (ws.value) {
            ws.value.close();
        }
    }

    const sendMessage = (message: Object) => {
        if (ws.value) {
            ws.value.send(JSON.stringify(message));
            console.log('[ws]发送消息', message);
        } else {
            console.error('[ws]未连接，无法发送消息');
        }
    }

    return {ws, connect, disConnect, sendMessage, unreadMessageCount, refreshUnreadMessageCount}
})